package member

import (
	"html/template"
	"log"

	"strings"

	"time"

	"awfan.cn/utils"

	"bytes"

	"net/http"

	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

func recover(format, mail string, w http.ResponseWriter, db *mgo.Database) {
	if mail == "" {
		utils.WriteError(format, 404, "#mail is empty", w)
		return
	}

	c := db.C(utils.PkgName(MEMBERS_XML{}))

	q := c.Find(bson.M{
		"mail": bson.RegEx{"^" + mail + "$", "i"},
	})

	var count int
	var err error

	if count, err = q.Count(); err != nil {
		utils.WriteError(format, 401, err.Error(), w)
		return
	}

	if count <= 0 {
		utils.WriteError(format, 402, "#mail not exist", w)
		return

	}
	var data = MEMBER_XML{}

	if err = q.One(&data); err != nil {
		utils.WriteError(format, 401, err.Error(), w)
		return
	}

	// exist
	var t *template.Template
	if t, err = template.ParseFiles(utils.AppPath() + "/html/html/password.txt"); err != nil {
		utils.WriteError(format, 401, err.Error(), w)
		return
	}

	type CODE_DATA struct {
		Nick     string
		Code     string
		DateTime time.Time
	}

	codedata := CODE_DATA{data.Name, utils.RandString(8), bson.Now()}

	var buf bytes.Buffer

	if err = t.Execute(&buf, codedata); err != nil {
		utils.WriteError(format, 401, err.Error(), w)
		return
	}

	if err := utils.Setting.Smtp.Mail("账号", "账号", utils.Setting.Smtp.Account, data.Mail, buf.String(), nil); err != nil {
		utils.WriteError(format, 500, err.Error(), w)
		return
	}

	if err := c.UpdateId(data.Id, bson.M{"$set": bson.M{"token": codedata.Code}}); err != nil {
		utils.WriteError(format, 500, err.Error(), w)
		return
	}

	utils.WriteEmpty(format, w)

	time.AfterFunc(time.Minute, func() {
		session, err := mgo.Dial("127.0.0.1")
		if err != nil {
			log.Println("#1 minute execute error: ", err.Error())
			return
		}

		defer session.Close()

		db := session.DB(utils.MONGO_DATABASE)

		c := db.C(utils.PkgName(MEMBERS_XML{}))

		if err := c.UpdateId(data.Id, bson.M{"$set": bson.M{"token": ""}}); err != nil {
			log.Println("#1 minute execute error: ", err.Error())
		}
	})
}

func recover2(format, code string, mail string, w http.ResponseWriter, db *mgo.Database) {
	if code == "" {
		utils.WriteError(format, 404, "#mail code is empty", w)
		return
	}

	if mail == "" {
		utils.WriteError(format, 404, "#mail is empty", w)
		return
	}

	var data = MEMBER_XML{}

	c := db.C(utils.PkgName(MEMBERS_XML{}))

	q := c.Find(bson.M{
		"mail": bson.RegEx{"^" + mail + "$", "i"},
	})

	var count int
	var err error
	if count, err = q.Count(); err != nil {
		utils.WriteError(format, 401, err.Error(), w)
		return
	}

	if count <= 0 {
		utils.WriteError(format, 402, "#mail not exist", w)
		return

	}

	if err := q.One(&data); err != nil {
		utils.WriteError(format, 401, err.Error(), w)
		return
	}

	if !strings.EqualFold(data.Token, code) {
		utils.WriteError(format, 405, "#code not match or expired", w)
		return
	}
	utils.WriteEmpty(format, w)
}
